import { Injectable } from '@angular/core';
import { Subject, Observer, Observable } from 'rxjs';
import { HttpService } from '../services/http.service';

@Injectable({
  providedIn: 'root'
})
export class WebsocketService {
  public isConnect = false;
  constructor(
    public HttpService: HttpService,
  ) { }
  ws: WebSocket;
  url:string;
  memberId:string;

  private heart: Subject<any> = new Subject<any>();//监听心跳
  private message: Subject<any> = new Subject<any>();
 
  setMember(memberId:string){
    this.memberId=memberId;
    this.url = this.HttpService.websockurl() + this.memberId;
  }

  getMember(){
    return this.memberId;
  }
   /**
    * 创建websocket
    * @param url 
    */
  createObservableScoket(url) {
      this.ws = new WebSocket(url);
      console.log(this.ws)
      // 返回成功时执行的方法
      this.ws.onmessage = (event)=>{
        this.isConnect = true;
        this.pong();
        this.analysisMessage(event.data)
      }
      // 返回错误时执行的方法
      this.ws.onerror = event => {console.log("websocket异常:"+event);this.createObservableScoket("")};
      // 关闭websocket流时执行的方法
      this.ws.onclose = event => {console.log("服务器关闭了链接");this.createObservableScoket("")};
  }

  /**
   * 
   * @param msg 发送消息
   */
  sendMessage(msg: any) {
    console.log("-----------发送消息---------------")
    console.log(msg);
    this.ws.send(JSON.stringify(msg));
  }

  
  /**
   * 返回心跳
   */
  getHeart(): Observable<any> {
    return this.heart.asObservable();
  }

  // this.heart.subscribe((res: number) => console.info("replay-subjectA ", res));
  /**
   * 返回消息
   */
  getMessage(): Observable<any> {
    return this.message.asObservable();
  }

  /**
   * 关闭websocket
   */
  closeWebSocket(){
    this.isConnect = false;
    console.log("关闭")
    this.ws.close();
  }
  /**
   * 发送心跳
   */
  pong(){
    let that = this;
    setInterval(() => {
      if(that.isConnect){
        console.log('发送垃圾数据')
        that.ws.send(JSON.stringify({
            userId:"1111-----------11111",
            code: '-1'
        }))
      }
    },10000)
  }

   /**
   * 解析返回值
   */
  analysisMessage(message:any){ 
      let messageJson=JSON.parse(message);
      if(messageJson.type==0){
        this.heart.next(messageJson);
      }else{
        this.message.next(messageJson);
      }
    
  } 

}
